import React from 'react';
import { Button, Table, Modal, message } from 'antd';

import Search from 'antd/lib/input/Search';
import { ColumnsType } from 'antd/lib/table';

import { checkPermission } from 'permission/Index';
import { BlackListInfo } from '../../../schema/BlackList';
import { getBlackLists, deleteBlackList, mulDelBlackList } from '../../../servers/servers';
import { clearNull, deleteRowChangePageNum, getTableIndex } from '../../../../utils/tools';
import { BlackListPop } from './component/BlackListPop';
import { BlackListImportPop } from './component/BlackListImportPop';
import './style.scss';
import moment from 'moment';

/**
 * 黑名单管理props
 */
interface IProps {}
/**
 * 黑名单管理state
 */
export interface IState {
  // 黑名单名称
  phoneNumber: string;
  // 新增黑名单抽屉控件显隐
  operationVisible: boolean;
  // 展示在table的数据
  tableData: BlackListInfo[];
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  tableLoading: boolean;
}

/**
 * 黑名单管理页
 */
class BlackList extends React.Component<IProps, IState> {
  /**
   * table列头
   * 因为table列头相对固定，不需要响应式地修改视图，所以记录在类的私有黑名单中而不是react state中，轻量的state利于提升性能
   */
  private columns: ColumnsType<BlackListInfo>;

  //子组件 黑名单操作 的引用
  private operationRef: React.RefObject<BlackListPop> | undefined;
  //子组件 黑名单操作 的引用
  private importRef: React.RefObject<BlackListImportPop> | undefined;

  // 已选id
  selectedIds: number[];
  constructor(props: IProps) {
    super(props);
    // 初始数据
    this.selectedIds = [];
    this.state = {
      phoneNumber: '',
      operationVisible: false,
      tableData: [],
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false,
    };

    this.columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        key: 'index',
        render: (text, record, index) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      {
        title: '黑名单号码',
        dataIndex: 'phoneNumber',
        key: 'phoneNumber',
      },
      {
        title: '导入时间',
        dataIndex: 'importTime',
        key: 'importTime',
        render: text => moment(Number(text)).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        render: (text, record, index) => {
          return this.renderOperation(text, record, index);
        },
      },
    ];
    this.operationRef = React.createRef();
    this.importRef = React.createRef();
  }

  public componentDidMount() {
    this.fetchList();
  }

  /**
   * 渲染操作按钮
   */
  private renderOperation(text: any, record: BlackListInfo, index: number): JSX.Element {
    return (
      <>
        {checkPermission('/client/blackList/delete') && (
          <Button
            type="link"
            onClick={() => {
              this.deleteRecord(record);
            }}
          >
            删除
          </Button>
        )}
      </>
    );
  }

  /**
   * 根据黑名单名称查询列表
   */
  private searchBlackList(name: string) {
    this.setState(
      {
        phoneNumber: name.trim(),
      },
      () => {
        this.jumpPage(1);
      }
    );
  }

  /**
   * 上传黑名单交互
   */
  private upload() {
    const modal = this.importRef?.current;
    modal && modal.open();
  }
  /**
   * 删除数据后更新
   */
  private deleteFresh(size: number) {
    const { pageTotal, pageNum, pageSize } = this.state.pageInfo;
    const newPageNum = deleteRowChangePageNum(size, pageTotal, pageNum, pageSize);
    this.setState(
      {
        pageInfo: {
          pageTotal,
          pageSize,
          pageNum: newPageNum,
        },
      },
      () => {
        this.fetchList();
      }
    );
  }
  /**
   * 删除黑名单交互
   */
  private deleteRecord(record: BlackListInfo) {
    Modal.confirm({
      content: '删除黑名单后无法恢复，确定删除吗',
      onOk: () => {
        deleteBlackList(record.blackListId)
          .then(res => {
            if (res.code === 0) {
              message.success('删除成功');
              this.deleteFresh(1);
            } else {
              message.error(`${res.tips}(错误码: ${res.code})`);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }
  /**
   * 批量删除
   */
  private batchDelete(): void {
    if (this.selectedIds.length === 0) {
      message.warn('请先选择项');
      return;
    }
    Modal.confirm({
      content: '删除后无法恢复，确认删除吗',
      onOk: () => {
        mulDelBlackList(this.selectedIds)
          .then(res => {
            message.success('删除成功');
            this.deleteFresh(this.selectedIds.length);
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }
  /**
   * 获取列表数据
   */
  private fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { phoneNumber, pageInfo } = this.state;
    getBlackLists(
      clearNull({
        phoneNumber: phoneNumber,
        pageNo: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
      })
    )
      .then(res => {
        this.setState({
          tableLoading: false,
        });
        pageInfo.pageTotal = res.count as number;
        this.setState({
          tableData: res.data,
          pageInfo: pageInfo,
        });
      })
      .catch(error => {
        this.setState({
          tableLoading: false,
        });
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }
  render() {
    const {
      tableData,
      tableLoading,
      pageInfo: { pageNum, pageSize, pageTotal },
    } = this.state;
    const rowSelection = {
      onChange: (selectedRowKeys: any, selectedRows: any) => {
        this.selectedIds = [];
        selectedRows.forEach((item: any) => {
          this.selectedIds.push(item.blackListId);
        });
      },
    };
    return (
      <>
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Search
              className="mgr-header-search"
              placeholder="请输入号码"
              enterButton="搜索"
              onSearch={value => this.searchBlackList(value)}
            />
          </div>
          <div className="mgr-header-right">
            {checkPermission('/client/blackList/add') && (
              <Button
                type="primary"
                onClick={() => {
                  this.operationRef?.current?.open();
                }}
              >
                新建号码
              </Button>
            )}
            {checkPermission('/client/blackList/upload') && (
              <Button
                type="primary"
                onClick={() => {
                  this.upload();
                }}
              >
                批量导入
              </Button>
            )}
            {checkPermission('/client/blackList/delete') && (
              <Button
                onClick={() => {
                  this.batchDelete();
                }}
              >
                批量删除
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            rowSelection={{ type: 'checkbox', ...rowSelection }}
            columns={this.columns}
            dataSource={tableData}
            rowKey="blackListId"
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <BlackListPop ref={this.operationRef} callback={() => this.jumpPage(1)} />
        <BlackListImportPop ref={this.importRef} callback={() => this.jumpPage(1)} />
      </>
    );
  }
}

export default BlackList;
